package dmsxl.zhanyuduilie;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

/**
 * Author: Zhang Dongwei
 * Date: 2023/5/3 20:34
 * 有效的括号
 */
public class zydl4_20 {

    public static void main(String[] args) {
//        String s = "()[]{}";
        String s = "]";
//        String s = "()[{}([])]{}";
//        String s = "(()[{}([])]{}";
        System.out.println(isValid(s));
    }

//    自己写的，效果一般
    public static boolean isValid1(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++){
            if (s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{'){
                stack.push(s.charAt(i));
            }else if (s.charAt(i)==')'){
                if (stack.isEmpty() || stack.pop() != '(')
                    return false;
            }else if (s.charAt(i)==']'){
                if (stack.isEmpty() || stack.pop() != '[')
                    return false;
            }else if (s.charAt(i)=='}'){
                if (stack.isEmpty() || stack.pop() != '{')
                    return false;
            }
        }
        if (!stack.isEmpty()) return false;
        return true;
    }

//    看的题解,效果很好
    public static boolean isValid(String s) {
        Deque<Character> deque = new LinkedList<>();
        for (int i = 0; i < s.length(); i++){
            if (s.charAt(i) == '('){
                deque.push(')');
            }else if (s.charAt(i) == '['){
                deque.push(']');
            }else if (s.charAt(i) == '{'){
                deque.push('}');
            }else if (deque.isEmpty() || deque.peek() != s.charAt(i)){
                return false;
            }else {
                deque.pop();
            }
        }
        return deque.isEmpty();
    }
}
